package com.h3c.ptability.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.util.IdWorker;
import com.eos.common.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Charsets;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.config.properties.ElectronicSignProperties;
import com.h3c.ptability.dto.DownloadFileDTO;
import com.h3c.ptability.dto.DownloadFileInfoDTO;
import com.h3c.ptability.dto.PtUploadFileDTO;
import com.h3c.ptability.entity.PtUploadFile;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtEsignRecordInfoService;
import com.h3c.ptability.service.IPtUploadFileService;
import com.h3c.ptability.utils.AppBusinessException;
import com.h3c.ptability.utils.AsposeUtil;
import com.h3c.ptability.utils.CommonUtil;
import com.h3c.ptability.utils.EncryptionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Copyright (C), 2022-2022, h3c
 * FileName: PtUploadFileController
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_upload_file controller
 * Version: 1.0
 */
@Api(tags = " PtUploadFile 接口")
@CrossOrigin
@Slf4j
@RestController
@RequestMapping(value = "/ptUploadFile", produces = "application/json;charset=utf-8")
public class PtUploadFileController {


    @Autowired
    CommService commService;
    @Resource
    private IPtUploadFileService ptUploadFileService;

    @Resource
    private IPtEsignRecordInfoService recordInfoService;

    @Resource
    private ElectronicSignProperties electronicSignProperties;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFileDTO", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public Result queryFuzzyListForPage(@ModelAttribute PtUploadFileDTO paramsDTO,
                                        @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //分页
        Page page = PageHelper.startPage(currentPage, pageSize);
        //执行
        List<PtUploadFileDTO> resultDTOList = ptUploadFileService.selectFuzzyByDto(paramsDTO);
        PageInfo<PtUploadFileDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(resultDTOList);
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(pageInfo));
        return new Result(true, 20000, "列表分页模糊查询成功", pageInfo);
    }

    /**
     * @title: queryListForPage
     * @description: 列表分页精确查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFileDTO", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryListForPage", method = RequestMethod.GET)
    public Result queryListForPage(@ModelAttribute PtUploadFileDTO paramsDTO,
                                   @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                   @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //分页
        Page page = PageHelper.startPage(currentPage, pageSize);
        //执行
        List<PtUploadFileDTO> resultDTOList = ptUploadFileService.selectFuzzyByDto(paramsDTO);
        PageInfo<PtUploadFileDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(resultDTOList);
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(pageInfo));
        return new Result(true, 20000, "列表分页查询成功", pageInfo);
    }

    /**
     * 根据busiType模糊查询 时间倒排
     *
     * @param paramsDTO
     * @return
     */
    @GetMapping("queryFileOrderByTime")
    public Result queryFileOrderByTime(@ModelAttribute PtUploadFileDTO paramsDTO,
                                       @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //分页
        Page page = PageHelper.startPage(currentPage, pageSize);
        //执行
        List<PtUploadFileDTO> resultDTOList = ptUploadFileService.queryFileOrderByTime(paramsDTO);
        PageInfo<PtUploadFileDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(resultDTOList);
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(pageInfo));
        return new Result(true, 20000, "列表分页查询成功", pageInfo);
    }


    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFile", paramType = "body")})
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody PtUploadFileDTO paramsDTO) {
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptUploadFileService.insertDto(paramsDTO);
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据插入成功", result);
    }

    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFile", paramType = "body")})
    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    public Result saveBatch(@RequestBody List<PtUploadFile> paramsDTO) {
        log.debug("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        String loginUserIdWithNoException = commService.getLoginUserIdWithNoException();
        Date now = new Date();
        //执行
        for (PtUploadFile dto : paramsDTO) {
            if (!StringUtils.hasText(dto.getFileId())) {
                dto.setFileId(String.valueOf(IdWorker.nextId()));
            }
            dto.setOperatorId(loginUserIdWithNoException);
            dto.setUploadTime(now);
        }
        ptUploadFileService.saveBatch(paramsDTO);
        log.info("执行 数据插入完成");
        return new Result(true, 20000, "数据插入成功");
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据修改", notes = "数据修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFile", paramType = "body")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@RequestBody PtUploadFileDTO paramsDTO) {
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptUploadFileService.updateDto(paramsDTO);
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据修改成功", result);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFile", paramType = "body")})
    public Result delete(@RequestBody PtUploadFileDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        //Integer result = ptUploadFileService.deleteDto(paramsDTO);
        String res = commService.deleteSfsFile(paramsDTO.getFileId());
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(res));
        return new Result(true, 20000, "数据删除", res);
    }

    /**
     * 删除链接方式的数据
     *
     * @param paramsDTO
     * @return
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtUploadFile", paramType = "body")})
    @RequestMapping(value = "/deleteUrlData", method = RequestMethod.POST)
    public Result deleteUrlData(@RequestBody PtUploadFileDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptUploadFileService.deleteUrlData(paramsDTO);
//        String res = commService.deleteSfsFile(paramsDTO.getFileId());
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据删除", result);
    }

    /**
     * 文件上傳返回上傳的文件id
     *
     * @return
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestPart("uploadFile") MultipartFile uploadFile,
                             @RequestParam(value = "clientIP", required = false) String clientIP,
                             @RequestParam(value = "busiType", required = false) String busiType,
                             @RequestParam(value = "busiId", required = false) String busiId,
                             @RequestParam(value = "appId") String appId,
                             @RequestParam(value = "operatorId") String operatorId,
                             @RequestParam(value = "operatorName") String operatorName
    ) {
        File file = null;
        try {
            file = new File("" + uploadFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file);
            String busiID = busiId != null ? busiId : "-1";
            String busiTyp = busiType != null ? busiType : "-1";
            String ip = clientIP != null ? clientIP : "-1";

//            String s = commService.uploadFileToSfsNew(file, appId, operatorId,busiID, busiTyp);
            PtUploadFile fileObj = commService.uploadFileToSfs(busiTyp, file, busiID, appId, operatorId);
            String fileId = fileObj.getFileId();
            ptUploadFileService.saveUploadHistory(uploadFile, appId, busiID, operatorId, operatorName, ip, uploadFile.getOriginalFilename());
            // commService.recordFileOperationLog(uploadFile.getOriginalFilename(), uploadFile.getSize(), FileOpTypeEnum.IMPORT);
            file.delete();
            HashMap<String, String> map = new HashMap<>(3);
            map.put("fileId", fileId);
            map.put("fileName", uploadFile.getOriginalFilename());
            return new Result(true, StatusCodeEnum.NORMAL, map);
        } catch (Exception e) {
            log.error("{}", e);
            throw new AppBusinessException("上传文件失败");
        } finally {
            if (file != null) {
                file.delete();
            }
        }
    }

    /**
     * 文件上傳返回上傳的文件id
     *
     * @return
     */
    @PostMapping("/uploadFileToSfs")
    public Result uploadFileToSfs(@RequestParam("uploadFile") MultipartFile uploadFile,
                                  @RequestParam(value = "clientIP", required = false) String clientIP,
                                  @RequestParam(value = "busiType", required = false) String busiType,
                                  @RequestParam(value = "busiId", required = false) String busiId,
                                  @RequestParam(value = "appId") String appId,
                                  @RequestParam(value = "operatorId") String operatorId,
                                  @RequestParam(value = "operatorName") String operatorName
    ) {
        File file = null;
        try {
            file = new File("" + uploadFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file);
            String busiID = busiId != null ? busiId : "-1";
            String busiTyp = busiType != null ? busiType : "-1";
            String ip = clientIP != null ? clientIP : "-1";

//            String s = commService.uploadFileToSfsNew(file, appId, operatorId,busiID, busiTyp);
            PtUploadFile fileObj = commService.uploadFileToSfs(busiTyp, file, busiID, appId, operatorId);
            ptUploadFileService.saveUploadHistory(uploadFile, appId, busiID, operatorId, operatorName, ip, uploadFile.getOriginalFilename());
            // commService.recordFileOperationLog(uploadFile.getOriginalFilename(), uploadFile.getSize(), FileOpTypeEnum.IMPORT);
            file.delete();
            return new Result(true, StatusCodeEnum.NORMAL, fileObj);
        } catch (Exception e) {
            log.error("{}", e);
            throw new AppBusinessException("上传文件失败");
        } finally {
            if (file != null) {
                file.delete();
            }
        }
    }

    @GetMapping("/previewOnline")
    public void previewOnline(@RequestParam("fileId") String fileId, HttpServletResponse response) {
        File downLoadFile = null;
        try {
            PtUploadFile fileObj = commService.getUploadFileById(fileId);
            String fileName = fileObj.getFileName();
            downLoadFile = commService.getFile(fileId, fileName, UserCache.getLoginUserDTO().getAccount());

            BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(CommonUtil.file2Bytes(downLoadFile)));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
                response.setHeader("Content-Type", "image/jpeg");
            } else if (fileName.endsWith("docx") || fileName.endsWith("xlsx") || fileName.endsWith("doc")) {
                response.setHeader("Content-Type", "text/html");
            }

            byte b[] = new byte[1024];
            int read;
            try {
                while ((read = bis.read(b)) != -1) {
                    bos.write(b, 0, read);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            } finally {
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new AppBusinessException("问卷预览出错，请稍后再试");
        }

    }

    @PostMapping(value = "/previewUploadFile")
    @ResponseBody
    public Result previewUploadFile(@RequestParam("fileId") String fileId, @RequestParam(value = "requestType", defaultValue = "0") String requestType,
                                    @RequestParam(value = "account", required = false) String account) {
        Map<String, String> previewFile = null;
        previewFile = commService.previewFile(fileId, account, requestType);

        return new Result(true, StatusCodeEnum.NORMAL, previewFile);
    }

    @PostMapping(value = "/deleteUploadFile")
    @ResponseBody
    public Result deleteUploadFile(
            @RequestParam("fileId") String fileId) {
        String res = commService.deleteSfsFile(fileId);

        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(res));
        return new Result(true, 20000, "数据删除", res);
    }

    @PostMapping(value = "/downloadFile")
    @ResponseBody
    public Result downloadFile(@RequestParam("fileId") String fileId,
                               @RequestParam(value = "fileName", required = false) String fileName,
                               @RequestParam(value = "account", required = false) String account) {
        try {
            File downLoadFile = commService.getFile(fileId, fileName, account);
            Map<String, String> result = new HashMap<>(2);
            result.put("file", Base64.encode(FileUtil.readBytes(downLoadFile)));
            if (StringUtils.hasText(fileName) && StringUtils.hasText(account) && !fileName.contains(".")) {
                int index = StrUtil.lastIndexOfIgnoreCase(downLoadFile.getName(), ".");
                String suffix = StrUtil.sub(downLoadFile.getName(), index, downLoadFile.getName().length());
                result.put("filename", fileName.concat("_").concat(DateUtil.today()).concat(suffix));
            } else {
                result.put("filename", StringUtils.hasText(fileName) ? fileName : downLoadFile.getName());
            }
            FileUtil.del(downLoadFile);
            return new Result(true, StatusCodeEnum.NORMAL, result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("下载失败");
        }
    }

    /**
     * 下载压缩包
     *
     * @param downloadFileDTO
     * @param response
     * @return
     */
    @PostMapping(value = "/downloadFileZip")
    @ResponseBody
    public void downloadFileZip(@Validated @RequestBody DownloadFileDTO downloadFileDTO,
                                HttpServletResponse response) {
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            String zipName = DateUtil.format(new Date(), "yyyyMMdd").concat("_")
                    .concat(StringUtils.hasText(downloadFileDTO.getAccountName()) ? downloadFileDTO.getAccountName() : "")
                    .concat(StringUtils.hasText(downloadFileDTO.getAccountId()) ? downloadFileDTO.getAccountId() : "");
            if (StringUtils.hasText(downloadFileDTO.getZipName())) {
                if (downloadFileDTO.getZipName().contains(".")) {
                    zipName = zipName.concat(downloadFileDTO.getZipName());
                } else {
                    zipName = zipName.concat(downloadFileDTO.getZipName()).concat(".zip");
                }
            } else {
                zipName = zipName.concat(".zip");
            }
            //设置响应头 需要编码否则中文乱码
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, Charsets.UTF_8.name()));
            response.setHeader("issuccess", "1");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition,issuccess");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            for (DownloadFileInfoDTO fileInfoDTO : downloadFileDTO.getDownloadFiles()) {
                File downLoadFile = commService.getFile(fileInfoDTO.getSfsId(), fileInfoDTO.getFileName(), downloadFileDTO.getAccount());
                int index = StrUtil.lastIndexOfIgnoreCase(downLoadFile.getName(), ".");
                String suffix = StrUtil.sub(downLoadFile.getName(), index, downLoadFile.getName().length());
                String fileName;
                if (StringUtils.hasText(fileInfoDTO.getFileName()) && StringUtils.hasText(downloadFileDTO.getAccountName())) {
                    fileName = fileInfoDTO.getFileName().concat("_")
                            .concat(StringUtils.hasText(downloadFileDTO.getAccountName()) ? downloadFileDTO.getAccountName() : "")
                            .concat(StringUtils.hasText(downloadFileDTO.getAccountId()) ? downloadFileDTO.getAccountId() : "")
                            .concat("_")
                            .concat(DateUtil.today()).concat(suffix);
                } else {
                    fileName = StringUtils.hasText(fileInfoDTO.getFileName()) ? fileInfoDTO.getFileName().concat(suffix) : downLoadFile.getName();
                }
                ZipEntry zipEntry = new ZipEntry(fileName);
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(FileUtil.readBytes(downLoadFile));
            }
        } catch (Exception e) {
            log.error("下载文件导出成压缩包失败:{}", e);
        }
    }

    @GetMapping(value = "/getSfsPicture")
    public Result getSfsPicture(@RequestParam("fileId") String fileId,
                                HttpServletResponse response) {
        InputStream stream = null;
        ServletOutputStream out = null;
        String fileName = RandomUtil.randomString(20);
        try {
            File downLoadFile = commService.getFile(fileId, fileName, electronicSignProperties.getDownloadSfsAccount());
            response.setContentType("image/jpeg");
            stream = new FileInputStream(downLoadFile);
            out = response.getOutputStream();
            byte buff[] = new byte[1024 * 10];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("下载失败");
        } finally {
            try {
                out.close();
                stream.close();
            } catch (Exception e) {
                log.error("异常:{}", e.getMessage());
            }
        }
        return null;
    }


    @GetMapping(value = "/downloadFileEncryption")
    public Result downloadFileEncryption(@RequestParam("fileId") String fileId,
                                         HttpServletResponse response) {
        InputStream stream = null;
        ServletOutputStream out = null;
        String fileName = RandomUtil.randomString(20);
        try {
            String realFileId = EncryptionUtil.getDecryptDataAES(fileId);
            File downLoadFile = commService.getFile(realFileId, fileName, electronicSignProperties.getDownloadSfsAccount());
            response.setContentType("application/x-download");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
            stream = new FileInputStream(downLoadFile);
            out = response.getOutputStream();
            byte buff[] = new byte[1024 * 10];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("下载失败");
        } finally {
            try {
                out.close();
                stream.close();
            } catch (Exception e) {
                log.error("异常:{}", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 电子签预览模板文件用
     * @param fileId
     * @param response
     * @return
     */
    @GetMapping(value = "/downloadElectronicSignFile")
    public Result downloadElectronicSignFile(@RequestParam("fileId") String fileId,
                                             HttpServletResponse response) {
        InputStream stream = null;
        ServletOutputStream out = null;
        String fileName = RandomUtil.randomString(20);
        File downLoadFile = null;
        File pdfFile = null;
        try {
            downLoadFile = commService.getFile(fileId, fileName, electronicSignProperties.getDownloadSfsAccount());
            int index = StrUtil.lastIndexOfIgnoreCase(downLoadFile.getName(), ".");
            String fileNameNoSuffix = StrUtil.sub(downLoadFile.getName(), 0, index);
            pdfFile = FileUtil.file(this.getClass().getResource("/").toString() + "/temp/callback/" + fileNameNoSuffix + ".pdf");
            AsposeUtil.wordToPdf(downLoadFile.getAbsolutePath(), pdfFile);
            response.setContentType("application/pdf");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNameNoSuffix, "UTF-8") + ".pdf");
            stream = new FileInputStream(pdfFile);
            out = response.getOutputStream();
            byte buff[] = new byte[1024 * 10];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("下载失败");
        } finally {
            try {
                out.close();
                stream.close();
                FileUtil.del(downLoadFile);
                FileUtil.del(pdfFile);
            } catch (Exception e) {
                log.error("异常:{}", e.getMessage());
            }
        }
        return null;
    }

    @GetMapping(value = "/downloadFile")
    public Result downloadFile(@RequestParam("fileId") String fileId,
                               HttpServletResponse response) {
        InputStream stream = null;
        ServletOutputStream out = null;
        String fileName = RandomUtil.randomString(20);
        try {
            File downLoadFile = commService.getFile(fileId, fileName, electronicSignProperties.getDownloadSfsAccount());
            response.setContentType("application/x-download");
            response.setCharacterEncoding("UTF-8");
            int index = StrUtil.lastIndexOfIgnoreCase(downLoadFile.getName(), ".");
            String suffix = StrUtil.sub(downLoadFile.getName(), index, downLoadFile.getName().length());
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + suffix);
            stream = new FileInputStream(downLoadFile);
            out = response.getOutputStream();
            byte buff[] = new byte[1024 * 10];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("下载失败");
        } finally {
            try {
                out.close();
                stream.close();
            } catch (Exception e) {
                log.error("异常:{}", e.getMessage());
            }
        }
        return null;
    }


    /**
     * 预览图片文件
     *
     * @param fileId 文件id
     */
    @GetMapping(value = "/previewUploadImgFile")
    @ResponseBody
    public void previewUploadImgFile(@RequestParam("fileId") String
                                             fileId, @RequestParam(value = "account", required = false) String account,
                                     HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)) {
            throw new AppBusinessException("参数错误");
        }
        String fileName = "";
        PtUploadFile uploadFile = commService.getUploadFileById(fileId);
        if (uploadFile == null) {
            fileName = UUID.fastUUID().toString();
        } else {
            fileName = uploadFile.getFileName();
        }
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        File downLoadFile = null;
        try {
            downLoadFile = commService.getFile(fileId, fileName, account);
            bos = new BufferedOutputStream(response.getOutputStream());
            bis = new BufferedInputStream(new FileInputStream(downLoadFile));
            response.setHeader("Content-Type", "image/jpeg");
            byte[] oneTimesArray = new byte[1024];
            int read;
            while ((read = bis.read(oneTimesArray)) != -1) {
                bos.write(oneTimesArray, 0, read);
            }
        } catch (IOException e) {
            log.error("写入流错误：", e);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (downLoadFile != null) {
                    if (downLoadFile.exists()) {
                        downLoadFile.delete(); //流关闭后删除文件
                    }
                }
            } catch (IOException e) {
                log.error("关闭流错误：", e);
            }
        }
    }
}
